<?php


namespace services\base;


use yii\data\Pagination;
use yii\db\Expression;
use yii\web\HttpException;
use common\components\Service;
use common\helpers\CommonHelper;
use common\models\rbac\Department;
use common\models\base\Profession;
use common\models\member\Attr;

class ProfessionService extends Service
{
    /**
     * 查找列表
     *
     * @param array $condition
     * @return array|\yii\db\ActiveRecord[]
     */
    public function findList(array $condition = [])
    {
        $query = Profession::find();

        // select
        isset($condition['select']) && $query->select($condition['select']);

        // condition
        isset($condition['id']) && $query->andWhere(['id' => $condition['id']]);
        isset($condition['status']) && $query->andWhere(['status' => $condition['status']]);

        return $query->asArray()->all();
    }

    /**
     * 数据查询
     *
     * @param int $id
     * @param int $page
     * @param int $limit
     * @return array|\yii\db\ActiveRecord[]
     * @author chenyuebin
     */
    public static function showData(int $id = 0, int $page = 0, int $limit = 0)
    {
        $query = Profession::find()
            ->alias('cf')
            ->leftJoin(Department::tableName() . ' dp', 'cf.department_id=dp.id')
            ->select([
                'cf.*',
                'dp.name dp_name',
                new Expression('FROM_UNIXTIME(cf.`created_at`, "%Y-%m-%d %H：%i") created_at'),
                new Expression('FROM_UNIXTIME(cf.`updated_at`, "%Y-%m-%d %H：%i") updated_at')
            ]);
        if ($id) {
            $res = $query->where(['cf.id' => $id])
                ->asArray()
                ->one();
            return $res;
        } else {
            $query->where(['!=', 'cf.status', Profession::STATUS_DELETE]);
            $pagination = new Pagination([
                'defaultPageSize' => $limit,
                'totalCount' => $query->count(),
            ]);
            $res = $query->offset($pagination->offset)
                ->orderBy('created_at desc')
                ->limit($pagination->limit)
                ->asArray()
                ->all();
            return [
                'list' => $res,
                'total' => (int)$pagination->totalCount,
                'pageSize' => (int)$limit,
                'page' => (int)$page
            ];
        }
    }

    /**
     * 获取项目列表
     *
     * @param $page
     * @param $limit
     * @return array
     * @author chenyuebin
     */
    public static function proList($page, $limit)
    {
        $query = Profession::find()
            ->where(['in', 'status', [Profession::STATUS_ENABLE, Profession::STATUS_DISABLE]])
            ->select(['*',
                new Expression('FROM_UNIXTIME(`created_at`, "%Y-%m-%d %H：%i") created_at'),
                new Expression('FROM_UNIXTIME(`updated_at`, "%Y-%m-%d %H：%i") updated_at')
            ]);
        $pagination = new Pagination([
            'defaultPageSize' => $limit,
            'totalCount' => $query->count(),
        ]);
        $ret = $query->offset($pagination->offset)
            ->limit($pagination->limit)
            ->orderBy(['status' => SORT_DESC, 'sort' => SORT_ASC])
            ->asArray()
            ->all();

        return [
            'list' => $ret,
            'total' => (int)$pagination->totalCount,
            'pageSize' => (int)$limit,
            'page' => (int)$page
        ];
    }

    /**
     * 检查岗位是否重复
     *
     * @param array $condition
     * @param int $id
     * @param int $type
     * @return bool
     * @author chenyuebin
     */
    public static function checkProfession(array $condition, int $id = 0, int $type = 1)
    {
        $query = Profession::find()
            ->where($condition)
            ->andWhere(['!=', 'status', Profession::STATUS_DELETE]);

        if ($id) {
            if ($type == 1) {
                $query->andWhere(['!=', 'id', $id]);
            } else {
                $query->andWhere(['id' => $id]);
            }
        }
        return $query->exists();
    }

    /**
     * 新增/编辑岗位
     *
     * @param array $params
     * @return bool
     * @throws \Exception
     * @author chenyuebin
     */
    public static function createUpdate(array $params)
    {
        if (isset($params['id'])) {
            $profession = Profession::findOne($params['id']);
            $profession->updated_at = time();
        } else {
            $profession = new Profession();
            $profession->created_at = time();
        }
        $profession->name = $params['name'];
        $profession->flag = $params['flag'];
        $profession->status = $params['status'];
        $res = $profession->save();
        if (!$res) {
            throw new \Exception(json_encode($profession->errors), 500);
        };

        return CommonHelper::api(200, 'success', $res);
    }

    /**
     * 新增岗位
     *
     * @param $params
     * @return bool
     */
    public static function proCreate(array $params)
    {
        //查询新建岗位是否重名
        $exists = self::checkProfession(['name' => $params['name']]);
        if ($exists) {
            return ['code' => 422, 'message' => '创建失败项目名重复',];
        }
        $profession = new Profession();

        foreach ($params as $key => $value) {
            $profession->$key = $value;
        }

        if ($profession->save()) {
            return ['code' => 200, 'message' => 'success',];
        }

        return ['code' => 422, 'message' => '创建失败',];
    }

    /**
     * 编辑岗位
     *
     * @param $params
     * @param $id
     * @return bool
     * @author chenyuebin
     */
    public static function proUpdate(array $params, int $id)
    {
        //查询是否重命名
        $model = Profession::find()
            ->select('id')
            ->where(['name' => $params['name']])
            ->andWhere(['!=', 'status', Profession::STATUS_DELETE])
            ->one();
        if ($model && $model->id != $id) {
            return ['code' => 422, 'message' => '岗位名重复',];
        }
        $profession = Profession::findOne($id);

        if ($profession->is_inhibit_delete == 1) {
            return ['code' => 422, 'message' => '改岗位不可编辑!',];
        }

        foreach ($params as $key => $value) {
            $profession->$key = $value;
        }
        if ($profession->save()) {
            // 更新员工属性岗位
            Attr::updateAll(['profession_name' => $params['name']], ['profession_id' => $profession->id]);

            return ['code' => 200, 'message' => 'success',];
        }

        return ['code' => 422, 'message' => '更新失败',];
    }

    /**
     * 删除岗位
     *
     * @param $id
     * @return bool
     * @throws HttpException
     * @author chenyuebin
     */
    public static function deletes($id)
    {
        try {
            $profession = Profession::findOne($id);

            if ($profession->is_inhibit_delete == 1) {
                return CommonHelper::api(422, '该岗位不可删除！');
            }
            $profession->status = Profession::STATUS_DELETE;
            $res = $profession->save();
            if ($res) {
                return CommonHelper::api(200, 'success', $res);
            }
        } catch (\Exception $exception) {
            throw new HttpException($exception->getCode(), $exception->getMessage());
        }
    }

    /**
     * 编辑项目状态
     *
     * @param int $id
     * @param int $status
     * @return array
     * @throws \Exception
     * @author wangxiang
     */
    public static function changeStatus(int $id, int $status)
    {
        $model = Profession::findOne($id);
        $model->status = $status;

        // 如果是不可改变的,直接跳过
        if ($model->is_inhibit_delete == 1) {
            return ['status' => $status, 'id' => $id];
        }

        if (!$model->save()) {
            throw new \Exception(json_encode($model->errors), 500);
        }

        return ['status' => $status, 'id' => $id];
    }
}
